<template>
	<om-addpage style="padding-top: 35px;" :menuName="menuName" @formSubmit="formSubmit" :busCode="busCode">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
	</om-addpage>
</template>

<script>
	import {
		getUrl,
		confirmModal,
		errorModal,
		ptFloat,
		minusF
	} from '@/static/js/common.js';
	import {
		buildFormData,
		formValidation,
		tranferToEditors,
		changeEditor,
		setSubmitSubValue,
		configSelectData,
		hasValue,
		hasEditor,
		getEditorTitle,
		changeConfigAttr,
		formShowLoading,
		getFormFields,
		formModelLoad,
		getWorkCacheKey
	} from '@/static/js/formUtil.js';
	import urlUtil from '@/static/js/urlUtil.js';
	import moment from '@/static/js/moment.js';
	import { mapState } from 'pinia';
	import {useLoginUserStore} from '@/stores/login-user.js';

	export default {
		data() {
			return buildFormData({
				buyerCache:'put-qg-requisitions-buyer-cache',
				purchaseUserCache:'put-qg-requisitions-purchaseUser-cache',
				instCache:'put-qg-requisitions-inst-cache',
				sluggishInstCache:'put-qg-requisitions-sluggishInst-cache',
				arrivedBatchesMax:0, // 批次
				arrivedBatchesMin:0,
				arrivalIntervalDaysMax:0, //天数
				arrivalIntervalDaysMin:0
			})
		},
		computed: {
			...mapState(useLoginUserStore, ['userName', 'userId','salaryInstId','salaryInstName'])
		},
		provide() {
			return {
				formPage: this
			}
		},
		methods: {
			clearPurchaseUser(){
				let _that = this
				_that.$refs.autoform.clear("title1","purchaseUserId")
				_that.$refs.autoform.clear("title1","purchaseZinstId")
				_that.$refs.autoform.changeEditor("title1","purchaseZinstId",'data',configSelectData([],'id','instName'))
			},
			getWorkParam(){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				return {
					arrivedBatchesMax:_that.arrivedBatchesMax, // 批次
					arrivedBatchesMin:_that.arrivedBatchesMin,
					arrivalIntervalDaysMax:_that.arrivalIntervalDaysMax, //天数
					arrivalIntervalDaysMin:_that.arrivalIntervalDaysMin,
					requirementTime:formdata.requirementTime,
					arrivedBatches:formdata.arrivedBatches,
					arrivalIntervalDays:formdata.arrivalIntervalDays,
					instId:formdata.instId,
					inst:formdata.inst,
					sluggishInstId:formdata.sluggishInstId,
					sluggishInstName:formdata.sluggishInstName
				}
			},
			onInputArrivedBatches(val){//输入次数
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				let num = Number(val)
				if(_that.arrivedBatchesMin+'' && num <_that.arrivedBatchesMin){
					formdata.arrivedBatches = _that.arrivedBatchesMin
				}
				if(_that.arrivedBatchesMax+'' && num >_that.arrivedBatchesMax){
					formdata.arrivedBatches = _that.arrivedBatchesMax
				}
			},
			onInutArrivalIntervalDays(val){ // 输入天数
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				let num = Number(val)
				if(!(val + '')){
					return
				}
				if(formdata.arrivedBatches && formdata.arrivedBatches == 1){
					let title = _that.$refs.autoform.getEditorTitle("title1","arrivedBatches")
					let title1 = _that.$refs.autoform.getEditorTitle("title1","arrivalIntervalDays")
					_that.om.toast(title+'为1时，'+title1+'不能存在数据')
					_that.$refs.autoform.clear("title1","arrivalIntervalDays")
					return
				}
				if(_that.arrivalIntervalDaysMin+'' && num <_that.arrivalIntervalDaysMin){
					formdata.arrivalIntervalDays = _that.arrivalIntervalDaysMin
				}
				if(_that.arrivalIntervalDaysMax+'' && num >_that.arrivalIntervalDaysMax){
					formdata.arrivalIntervalDays = _that.arrivalIntervalDaysMax
				}
			},
			onInputRequirementTime(val){
				let _that = this
				let formdata = _that.$refs.autoform.formdata
				if(formdata.purchaseTime){
					if(moment(val).isBefore(formdata.purchaseTime)){
						let title = _that.$refs.autoform.getEditorTitle("title1","purchaseTime")
						let title1 = _that.$refs.autoform.getEditorTitle("title1","requirementTime")
						errorModal(_that,'提示信息',title1+'间不能早于'+title+formdata.purchaseTime,()=>{
							_that.$refs.autoform.clear("title1","requirementTime")
						})
					}else{
						formdata.lastRequirementTime = val
					}
				}
			},
			clearBuyer(){
				let _that = this
				_that.$refs.autoform.clear("title1","institutionId")
				_that.$refs.autoform.clear("title1","buyerId")
				_that.$refs.autoform.changeEditor("title1","institutionId",'data',configSelectData([],'id','instName'))
			},
			findInstByUserIdOrPostId(id,filedId){
				let _that = this
				_that.om.request(
					'orgInstPosUserOfficial/findInstByUserIdOrPostId',
					{
						userId:id
					}
				).then(res=>{
					_that.$refs.autoform.changeEditor("title1",filedId,'data',configSelectData(res,'id','instName'))
					_that.$refs.autoform.initSelectIndex("title1",filedId)
				})
			},
			initLoad(options) {
				let _that = this;
				let fileId = options.fileId
				let ajaxArr = [
					{
						url:'orgInstPosUserOfficial/findInstByUserIdOrPostId',
						param:{
							userId:_that.userId
						}
					},
					{
						url:'dataDict/getDataByCode1',
						param:{
							code:'DD034010001'
						}
					},
					{
						url:'dataDict/getDataByCode1',
						param:{
							code:'DD034010002'
						}
					},{
						url:'currencyDict/getLocalCurrency',
						param:{},
						method:'post'
					}
				]
				if(fileId){
					ajaxArr.push(
						{
							url:'requisitions/getValue',
							param:{
								fileId:fileId
							}
						}
					)
				}
				formModelLoad(ajaxArr, function(res, mainData) {
					if(res[1].succeed){
						_that.arrivedBatchesMax = res[1].value.maxNum
						_that.arrivedBatchesMin = res[1].value.minNum
					}
					changeEditor("title1","arrivedBatches",{
						defaultValue:res[1].value.minNum,
						defaultName:res[1].value.minNum
					},null,mainData)
					if(res[2].succeed){
						_that.arrivalIntervalDaysMax = res[2].value.maxNum
						_that.arrivalIntervalDaysMin = res[2].value.minNum
					
					}
					if(res[3].succeed){
						changeEditor("title1","currencyId",{
							defaultName:res[3].value.codeNameUnit,
							defaultValue:res[3].value.id
						},null,mainData)
					}
					changeEditor("title1","institutionId",'data',configSelectData(res[0],'id','instName'),mainData)
					changeEditor("title1","institutionId",{
						defaultName:_that.salaryInstName,
						defaultValue:_that.salaryInstId
					},null,mainData)
					changeEditor("title1","instId",{
						defaultName:_that.salaryInstName,
						defaultValue:_that.salaryInstId
					},null,mainData)
					changeEditor("title1","sluggishInstId",{
						defaultName:_that.salaryInstName,
						defaultValue:_that.salaryInstId
					},null,mainData)
					changeEditor("title1","buyerId",{
						defaultName:_that.userName,
						defaultValue:_that.userId 
					},null,mainData)
					changeEditor("title1","buyerId",{
						"link":'../../public/searchUser/searchUser',
						"linkParam":{
							other:JSON.stringify({
							}),
							isSingle:true,
							isUserPos:true,
							isNew:true,
							cachename:_that.buyerCache
						}
					},null,mainData)
					changeEditor("title1","purchaseUserId",{
						"link":'../../public/searchUser/searchUser',
						"linkParam":{
							other:JSON.stringify({
							}),
							isSingle:true,
							isUserPos:true,
							isNew:true,
							cachename:_that.purchaseUserCache
						}
					},null,mainData) 
						
					changeEditor("title1","instId",{
						"link":'../../public/search/search',
						"linkParam":{
							other:JSON.stringify(),
							url:'tinstitution/getComboTree',
							namefield:'text',
							initload:true,
							cachename:_that.instCache
						}
					},null,mainData)
					changeEditor("title1","sluggishInstId",{
						"link":'../../public/search/search',
						"linkParam":{
							other:JSON.stringify(),
							url:'tinstitution/getComboTree',
							namefield:'text',
							initload:true,
							cachename:_that.sluggishInstCache
						}
					},null,mainData)
					changeEditor("title1","requirementTime",'noInitDate',true,mainData)
					if(_that.subEditorObj["title2"]){
						let attr = {
							getWorkParam:'getWorkParam'
						}
						let configData = _that.subConfigData["title2"]
						if(hasEditor("title2","newProductId",configData)){
							let title = getEditorTitle("title2","newProductId",configData)
							attr.titleTemplate = title+':<%=newProductCode || "未填写"%>'
						}
						changeEditor("title2","dataStr",attr,mainData)
					}
					if(fileId){
						let fieldArr = getFormFields(mainData)
						fieldArr.push('id')
						for(let index in res[4].value){
							if(fieldArr.includes(index)){
								_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[4].value[index])
								_that.$set(_that.formdata,index,res[4].value[index])
							}
						}
						if(_that.subEditorObj["title2"]){
							let dataList = _that._.cloneDeep(res[4].value.requisitionsBodyDTOS)
							_that.subEditorObj["title2"].workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata,"dataStr",JSON.stringify(dataList))
							_that.$set(_that.formdata,"dataStr",JSON.stringify(dataList))
						}
					}
					_that.$nextTick(function(){
						if(_that.$refs.autoform.formdata.buyerId){
							_that.findInstByUserIdOrPostId(_that.$refs.autoform.formdata.buyerId,'institutionId')
						}
						if(_that.$refs.autoform.formdata.purchaseUserId){
							_that.findInstByUserIdOrPostId(_that.$refs.autoform.formdata.purchaseUserId,'purchaseZinstId')
						}
					})
				}, options)
			},
			formSubmit() {
				let _that = this
				if(!_that.edit){
					_that.om.formSave('requisitions/doAdd',_that.formdata,_that)
				}else{
					_that.om.formSave('requisitions/doUpdate',_that.formdata,_that)
				}
			}
		},
		onUnload(){
		//#ifdef APP-PLUS
			let _that = this;
			if (_that.$refs.autoform) {
				for (let fieldId in _that.subEditorObj) {
					uni.removeStorage({
						key: getWorkCacheKey(fieldId)
					});
				}
			}
		//#endif
		},
		onLoad(options) {
			this.initValue.userinfoId = this.userId
			this.initLoad(options)
		},
		onShow() {
			let _that = this;
			if (_that.$refs.autoform) {
				for (let fieldId in _that.subEditorObj) {
					var editor = _that.subEditorObj[fieldId];
					uni.getStorage({
						key: getWorkCacheKey(fieldId),
						success: function(res) {
							editor.workList = res.data;
							if(fieldId == 'title2'){
								let formdata = _that.$refs.autoform.formdata
								for(let item of _that.subEditorObj[fieldId]){
									if(item.instId && item.instId != formdata.instId){
										_that.$refs.autoform.clear("title1","instId")
									}
									if(item.sluggishResponsiblePartiesId && item.sluggishResponsiblePartiesId != formdata.sluggishInstId){
										_that.$refs.autoform.clear("title1","sluggishInstId")
									}
								}
							}
							uni.removeStorage({
								key: getWorkCacheKey(fieldId)
							});
						}
					});
				}
				uni.getStorage({
					key:_that.buyerCache,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.buyerId = d.id
							formdata.buyer = d.username
							formdata.institutionId = d.instId
							formdata.institutionName = d.instName
							_that.findInstByUserIdOrPostId(d.id,'institutionId')
							uni.removeStorage({
								key:_that.buyerCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.purchaseUserCache,
					success:(res)=>{
						if(res.data){
							let d = res.data[0]
							let formdata = _that.$refs.autoform.formdata
							formdata.purchaseUserId = d.id
							formdata.purchaseUserName = d.username
							formdata.purchaseZinstId = d.instId
							formdata.purchaseZinstName = d.instName
							_that.findInstByUserIdOrPostId(d.id,'purchaseZinstId')
							uni.removeStorage({
								key:_that.purchaseUserCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.instCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.instId = d.id
							formdata.inst = d.text
							if(_that.subEditorObj["title2"]){
								if(_that.subEditorObj['title2'].workList.length > 0){
									for(let item of _that.subEditorObj['title2'].workList){
										item.instId = d.id
										item.inst = d.text
										_that.om.toast('子表已更新')
									}
								}
							}
							uni.removeStorage({
								key:_that.instCache
							})
						}
					}
				})
				uni.getStorage({
					key:_that.sluggishInstCache,
					success:(res)=>{
						if(res.data){
							let d = res.data
							let formdata = _that.$refs.autoform.formdata
							formdata.sluggishInstId = d.id
							formdata.sluggishInstName = d.text
							if(_that.subEditorObj["title2"]){
								if(_that.subEditorObj['title2'].workList.length > 0){
									for(let item of _that.subEditorObj['title2'].workList){
										item.sluggishResponsiblePartiesId = d.id
										item.sluggishResponsibleParties = d.text
										_that.om.toast('子表已更新')
									}
								}
							}
							uni.removeStorage({
								key:_that.sluggishInstCache
							})
						}
					}
				})
			}
		}
	}
</script>

<style>
</style>
       